package uit.nfcmenu.services;

import java.util.ArrayList;
import java.util.Date;

import uit.nfcmenu.models.*;
import uit.nfcmenu.utils.CommConstant;
import uit.nfcmenu.utils.CommUrl;
import uit.nfcmenu.utils.JSONParser;
import uit.nfcmenu.utils.NetworkHelper;
import uit.nfcmenu.utils.WebserviceHelper;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class GetOrdersAsyncTask extends
		AsyncTask<String, ArrayList<OrderModel>, Void> {
	public static final String tag = GetOrdersAsyncTask.class.getSimpleName();

	// ===========================================
	// Fields
	// ===========================================

	ArrayList<OrderModel> mOrders;
	DatabaseManager mDBManager;
	Context mContext;

	boolean mIsRunning;

	static GetOrdersAsyncTask mInstance;

	// ===========================================
	// Constructors, System Methods, Event Methods
	// ===========================================
	public GetOrdersAsyncTask(DatabaseManager dbManager, Context context) {
		mDBManager = dbManager;
		mContext = context;
		mIsRunning = false;
	}
	
	private void pushrequest(){
		while (CommConstant.request.size()>0){
			String url=CommConstant.request.remove(0);
			String response = WebserviceHelper.callWS(url);
		}
	}

	public static GetOrdersAsyncTask getInstance(DatabaseManager dbManager,
			Context context) {
		if (mInstance == null)
			mInstance = new GetOrdersAsyncTask(dbManager, context);
		return mInstance;
	}

	@Override
	protected Void doInBackground(String... params) {
		Log.i(tag, "doInBackground()");
		mIsRunning=true;
		long nexttime = System.currentTimeMillis()
				+ CommConstant.TIME_PAUSE_UPDATE_DATA;
		while (mIsRunning) {
			Log.i(tag, "be in loop...");
//			long current = System.currentTimeMillis();
//			if (current >= nexttime) {
				// mOrders = getOrderInTest(mContext);
				Log.i(tag, "check data");
//				nexttime = current + CommConstant.TIME_PAUSE_UPDATE_DATA;

				if (NetworkHelper.checkNetworkStatus(mContext)) {
					pushrequest();
					mOrders = getOrderFromServer();
					if (mOrders != null) {
						// handle data // insert data to db
						if(mDBManager==null){
							break;
						}
						mDBManager.updateOrders(mOrders);
						// check change data
						mDBManager.notifyDataChanged();
					} else {
						Log.w(tag, "there are errors in  getting data");
					}
				}
//			}

			 try {
			 Thread.sleep(CommConstant.TIME_PAUSE_UPDATE_DATA); // pause
			 } catch (InterruptedException e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
			 }
		}
		Log.i(tag, "end of doInBackground");
		mIsRunning=false;
		return null;
	}

	private ArrayList<OrderModel> getOrderFromServer() {
		ArrayList<OrderModel> menus = new ArrayList<OrderModel>();
		if (NetworkHelper.checkNetworkStatus(mContext)) {
			menus = new ArrayList<OrderModel>();
			// get url
			String apiUrl = CommUrl.createUrlGetOrderInServer();
			// get date from web-service
			String response = WebserviceHelper.callWS(apiUrl);
			// parse data
			String time = null;
			menus = JSONParser.parseOrders(response, time);
			Log.i(tag, "" + time);
			// ttnlan
			// check data changed ?
			// check time update in share preference
			/*
			 * if (time in share pre == null){ { store new one }
			 * 
			 * if (dataChanged){ store new one call WS getAllFoodAndDrink();
			 * store new items into database }
			 */
			SharedPreferences mPreferences = mContext.getSharedPreferences(
					"lasttime", mContext.MODE_PRIVATE);
			String lasttime = mPreferences.getString("lastupdate", null);
			if (lasttime == null) { // first time

			} else {
				Date dLasttime = CommConstant.parsefromString(lasttime);
				Date today = CommConstant
						.parsefromString(CommConstant.Timeupdate);
				if (today.after(dLasttime)) {
					// handle data
					// SharedPreferences.Editor editor = mPreferences.edit();
					// editor.putString("lastupdate",
					// CommConstant.parseFromdate(today));
					// editor.commit();
					// update all menu and item
					mDBManager.getAllMenuFromServer();
					mDBManager.getAllItemsFromServer();
				} else {

				}
			}
			return menus;
		}
		Log.i(tag, "NetWork error");
		return null;
	}

	/**
	 * Get data from Server by network
	 * 
	 * @return
	 */
	private ArrayList<MenuModel> getMenuFromServer() {
		if (NetworkHelper.checkNetworkStatus(mContext)) {
			ArrayList<MenuModel> menus = new ArrayList<MenuModel>();
			// get url
			String apiUrl = CommUrl.createUrlGetMainMenuInServer();
			// get date from web-service
			String response = WebserviceHelper.callWS(apiUrl);
			// parse data
			menus = JSONParser.parseMenus(response);
			return menus;
		}
		return null;
	}

	/**
	 * Get data for testing
	 * 
	 * @param context
	 * @return
	 */
	private ArrayList<MenuModel> getMenuInTest(Context context) {
		ArrayList<MenuModel> menus = new ArrayList<MenuModel>();
		// get date from web-service
		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
				"visual_data/menu.json"); // get from assets
		// parse data
		menus = JSONParser.parseMenus(response);
		return menus;
	}

	private ArrayList<ItemModel> getItemInTest(Context context) {
		ArrayList<ItemModel> items = new ArrayList<ItemModel>();
		// get date from web-service
		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
				"visual_data/item.json"); // get from assets
		// parse data
		items = JSONParser.parseItems(response);
		return items;
	}

	private ArrayList<OrderModel> getOrderInTest(Context context) {
		ArrayList<OrderModel> orders = new ArrayList<OrderModel>();
		// get date from web-service
		String response = WebserviceHelper.callTestInsteadWSByAssets(context,
				"visual_data/order.json"); // get from assets
		// parse data
		orders = JSONParser.parseOrders(response, ""); // TODO
		return orders;
	}

	/*
	 * Other
	 */
	// @Override
	// protected void onProgressUpdate(ArrayList<OrderModel>... values) {
	// if (values != null) {
	// mDBManager.insertOrderStates(values[0]);
	// // check item
	// }
	// else {
	// Log.w(tag, "there are errors in  getting data");
	// }
	// super.onProgressUpdate(values);
	// }

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
	}

	// ===========================================
	// Action Methods
	// ===========================================

	public boolean stop() {
		Log.d(tag, "stop()");
		if (mIsRunning) {
			mIsRunning = false;
		}
		return mIsRunning;
	}

	public boolean isRunning() {
		// TODO Auto-generated method stub
		return mIsRunning;
	}

	// ===========================================
	// Getters, Setters
	// ===========================================

}
